const Koa = require('koa')
const path = require('path')
const convert = require('koa-convert')
// const bodyParser = require('koa-bodyparser') // 会把请求题放到ctx.request.body
const betterParser = require('koa-better-body') //  会把请求题放到ctx.request.fileds
const app = new Koa()
// app.use(bodyParser())
app.use(convert(betterParser({
    uploadDir: path.resolve(__dirname, 'uploads')
})))
console.log(path.join(__dirname, 'uploads'),'path.join(__dirname, "./uploads")');
console.log(path.resolve(__dirname, 'uploads'),'path.resolve(__dirname, "./uploads")');


app.use(async (ctx, next) => {
    if (ctx.url == '/user' && ctx.method == 'GET') {
        ctx.set('Content-Type','text/html;charset=utf8')
        ctx.body = (
            `
                <form method="POST" enctype="multipart/form-data">
                    <input type="text" name="username" />
                    <input type="file" name="avarta" />
                    <input type="submit" />
                </form>
            `
        )
    }else { await next()}
})

app.use(async (ctx, next) => { 
    if (ctx.url == '/user' && ctx.method == 'POST') { 
        console.log(ctx.request)
        console.log(ctx.request.fields)
        ctx.body = ctx.request.fields
        
    }else { await next()}
})

app.listen(8080)